﻿using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using System;
using System.Collections.Generic;
using System.Data.Entity;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Web;
using System.Web.Http;
using System.Web.Http.Results;
using WPS.Code.Code;
using WPS.Code.Utils;
using WPS.Log;
using WPS.Model;
using WPS.SDK.model.oauth;
using WPS.SDK.openapi;

namespace WPS.Web.Controllers
{
    public class OauthController : ApiController
    {
        #region 用户同意授权，获取code
        /// <summary>
        /// 用户同意授权，获取code
        /// </summary>
        /// <returns></returns>
        [HttpGet, Route("authorize/url")]
        public JsonResult<Response> GetAuthorizeUrl()
        {
            LogHelper.Info("进入authorize/url");
            try
            {
                string token = string.Empty;
                WPSUserInfo userInfo = null;
                HttpContextBase httpContextBase = (HttpContextBase)Request.Properties["MS_HttpContext"];
                if (httpContextBase == null)
                {
                    return Json<Response>(ApiUtils.DoResponse(ResponseCode.Fail, null, "MS_HttpContext参数为null."));
                }
                HttpRequestBase request = httpContextBase.Request;
                if (request["token"] == null)
                {
                    return Json<Response>(ApiUtils.DoResponse(ResponseCode.Fail, null, "token为空."));
                }
                token = request["token"].ToString();
                userInfo = CacheUtils.Get<WPSUserInfo>(token);
                if (userInfo == null)
                {
                    return Json<Response>(ApiUtils.DoResponse(ResponseCode.Fail, null, "找不到相关的用户信息."));
                }
                List<string> listScope = new List<string>();
                listScope.Add(WPSScope.WPSUserInfo);
                listScope.Add(WPSScope.Vas);
                listScope.Add(WPSScope.CloudFile);
                listScope.Add(WPSScope.FileSelector);
                //  string redirectUri = WPSConfig.Download_Host + "/authorize/token?token=" + token;
                string redirectUri = WPSConfig.Download_Host+"/wpslist.html?token=" + token;
                redirectUri = HttpUtility.HtmlEncode(redirectUri);
                string param = "?response_type=code&appid=" + WPSOauthConfig.AppId + "&autologin=false&redirect_uri=" + redirectUri + "&scope=" + string.Join(",", listScope.ToArray()) + "&state=STATE";
                string authorizeUrl = WPSOauthConfig.Authorization_Url + param;
                JObject jsonObject = new JObject();
                jsonObject["authorize_url"] = authorizeUrl;
                LogHelper.Info("authorize_url：" + authorizeUrl);
                LogHelper.Info("离开authorize/url");
                return Json<Response>(ApiUtils.DoResponse(ResponseCode.Success, jsonObject, ""));
            }
            catch (Exception e)
            {
                LogHelper.Error(e.Message);
                return Json<Response>(ApiUtils.DoResponse(ResponseCode.Fail, "", e.Message));
            }
        }
        #endregion

        #region 通过code换取网页授权access_token
        /// <summary>
        /// 通过code换取网页授权access_token
        /// </summary>
        /// <returns></returns>
        [HttpGet, Route("authorize/token")]
        public JsonResult<Response> GetAuthorizeToen()
        {
            LogHelper.Info("进入authorize/token");
            try
            {
                string token = string.Empty;
                string code = string.Empty;
                WPSUserInfo userInfo = null;
                HttpContextBase httpContextBase = (HttpContextBase)Request.Properties["MS_HttpContext"];
                if (httpContextBase == null)
                {
                    return Json<Response>(ApiUtils.DoResponse(ResponseCode.Fail, null, "MS_HttpContext参数为null."));
                }
                HttpRequestBase request = httpContextBase.Request;
                if (request["token"] == null)
                {
                    return Json<Response>(ApiUtils.DoResponse(ResponseCode.Fail, null, "token为空."));
                }
                token = request["token"].ToString();
                if (request["code"] == null)
                {
                    return Json<Response>(ApiUtils.DoResponse(ResponseCode.Fail, null, "code为空."));
                }
                code = request["code"].ToString();
                userInfo = CacheUtils.Get<WPSUserInfo>(token);
                if (userInfo == null)
                {
                    return Json<Response>(ApiUtils.DoResponse(ResponseCode.Fail, null, "找不到相关的用户信息."));
                }
                string accessToken = string.Empty;
                LogHelper.Info("code ："+ code);
                LogHelper.Info("进入OAuth2.getToken");
                Token wpsToken = OAuth2.getToken(WPSOauthConfig.AppId, WPSOauthConfig.AppKey, code);
                LogHelper.Info("离开OAuth2.getToken");
                String key = userInfo.ID + "_wps_token_" + wpsToken.openid;
                String refreshkey = userInfo.ID + "_wps_refreshtoken_" + wpsToken.openid;
                LogHelper.Info("key ：" + wpsToken.accessToken + ";<br/>refreshkey："+ wpsToken.refreshToken);
                CacheUtils.Set<string>(key, wpsToken.accessToken, DateTime.Now.AddMilliseconds(wpsToken.expiresIn - 20000));
                CacheUtils.Set<string>(refreshkey, wpsToken.refreshToken, DateTime.Now.AddDays(90));
                accessToken = wpsToken.accessToken;
                using (WPSModel context = new WPSModel())
                {
                    AuthorizeInfo authorizeInfo = context.AuthorizeInfo.Where(a => a.USER_ID == userInfo.ID).FirstOrDefault();
                    if (authorizeInfo == null)
                    {
                        authorizeInfo = new AuthorizeInfo();
                        authorizeInfo.USER_ID = userInfo.ID;
                        authorizeInfo.ID = Guid.NewGuid().ToString();
                        context.Entry<AuthorizeInfo>(authorizeInfo).State = EntityState.Added;
                    }
                    authorizeInfo.OPEN_ID = wpsToken.openid;
                    authorizeInfo.APP_ID = wpsToken.appid;
                    context.SaveChanges();
                }
                JObject jsonObject = new JObject();
                jsonObject["access_token"] = accessToken;
                LogHelper.Info("离开authorize/token");
                return Json<Response>(ApiUtils.DoResponse(ResponseCode.Success, jsonObject, ""));
            }
            catch (Exception e)
            {
                LogHelper.Error("authorize/token："+e.Message+"<br/>"+e.StackTrace);
                return Json<Response>(ApiUtils.DoResponse(ResponseCode.Fail, "", e.Message));
            }
        }
        #endregion

        #region 获取缓存中的access_token
        [HttpPost, Route("authorize/cachetoken")]
        public JsonResult<Response> GetCacheAccessToken()
        {
            try
            {
                LogHelper.Info("进入authorize/cachetoken");
                string token = string.Empty;
                string accessToken = string.Empty;
                WPSUserInfo userInfo = null;
                HttpContextBase httpContextBase = (HttpContextBase)Request.Properties["MS_HttpContext"];
                if (httpContextBase == null)
                {
                    return Json<Response>(ApiUtils.DoResponse(ResponseCode.Fail, null, "MS_HttpContext参数为null."));
                }
                HttpRequestBase request = httpContextBase.Request;
                if (request["token"] == null)
                {
                    return Json<Response>(ApiUtils.DoResponse(ResponseCode.Fail, null, "token为空."));
                }
                token = request["token"].ToString();
                userInfo = CacheUtils.Get<WPSUserInfo>(token);
                if (userInfo == null)
                {
                    return Json<Response>(ApiUtils.DoResponse(ResponseCode.Fail, null, "找不到相关的用户信息."));
                }
                using (WPSModel context = new WPSModel())
                {
                    AuthorizeInfo authorizeInfo = context.AuthorizeInfo.Where(a => a.USER_ID == userInfo.ID).FirstOrDefault();
                    if (authorizeInfo == null)
                    {
                        return Json<Response>(ApiUtils.DoResponse(ResponseCode.Fail, null, "找不到相关的授权信息，请先授权."));
                    }
                    accessToken = WpsUtils.getAccessToken(authorizeInfo.USER_ID, authorizeInfo.OPEN_ID);
                }
                JObject jsonObject = new JObject();
                jsonObject["access_token"] = accessToken;
                LogHelper.Info("离开authorize/cachetoken");
                return Json<Response>(ApiUtils.DoResponse(ResponseCode.Success, jsonObject, ""));
            }
            catch (Exception e)
            {
                LogHelper.Error("authorize/cachetoken：" + e.Message + "<br/>" + e.StackTrace);
                return Json<Response>(ApiUtils.DoResponse(ResponseCode.Fail, "", e.Message));
            }
        }
        #endregion

        #region 拉取用户信息
        [HttpGet, Route("authorize/userInfo")]
        public JsonResult<Response> GetUserInfo()
        {
            try
            {
                LogHelper.Info("进入authorize/userInfo");
                JObject jsonObject = new JObject();
                string token = string.Empty;
                string accessToken = string.Empty;
                WPSUserInfo userInfo = null;
                HttpContextBase httpContextBase = (HttpContextBase)Request.Properties["MS_HttpContext"];
                if (httpContextBase == null)
                {
                    return Json<Response>(ApiUtils.DoResponse(ResponseCode.Fail, null, "MS_HttpContext参数为null."));
                }
                HttpRequestBase request = httpContextBase.Request;
                if (request["token"] == null)
                {
                    return Json<Response>(ApiUtils.DoResponse(ResponseCode.Fail, null, "token为空."));
                }
                token = request["token"].ToString();
                userInfo = CacheUtils.Get<WPSUserInfo>(token);
                if (userInfo == null)
                {
                    return Json<Response>(ApiUtils.DoResponse(ResponseCode.Fail, null, "找不到相关的用户信息."));
                }
                using (WPSModel context = new WPSModel())
                {
                    AuthorizeInfo authorizeInfo = context.AuthorizeInfo.Where(a => a.USER_ID == userInfo.ID).FirstOrDefault();
                    if (authorizeInfo == null)
                    {
                        return Json<Response>(ApiUtils.DoResponse(ResponseCode.Fail, null, "找不到相关的授权信息，请先授权."));
                    }
                    accessToken = WpsUtils.getAccessToken(authorizeInfo.USER_ID, authorizeInfo.OPEN_ID);
                    UserInfo wpsUserInfo = OAuth2.getUserInfo(accessToken, authorizeInfo.OPEN_ID);
                    authorizeInfo.APP_ID = WPSOauthConfig.AppId;
                    authorizeInfo.AVATAR = wpsUserInfo.avatar;
                    authorizeInfo.NICE_NAME = wpsUserInfo.nickname;
                    authorizeInfo.SEX = wpsUserInfo.sex;
                    authorizeInfo.UNIOIN_ID = wpsUserInfo.unionid;
                    context.SaveChanges();

                    JObject userObject = new JObject();
                    userObject["nickname"] = wpsUserInfo.nickname;
                    userObject["avatar"] = wpsUserInfo.avatar;
                    userObject["sex"] = wpsUserInfo.sex;
                    jsonObject["user"] = userObject;
                }
                LogHelper.Info("离开authorize/userInfo");
                return Json<Response>(ApiUtils.DoResponse(ResponseCode.Success, jsonObject, ""));
            }
            catch (Exception e)
            {
                LogHelper.Error("authorize/userInfo：" + e.Message + "<br/>" + e.StackTrace);
                return Json<Response>(ApiUtils.DoResponse(ResponseCode.Fail, "", e.Message));
            }
        }

        #endregion

    }
}